package com.starlink.service.impl;

import com.starlink.mapper.StreetMapper;
import com.starlink.model.vo.AddressTreeVO;
import com.starlink.service.CommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: zyh
 * @date: 2023-07-04
 */
@Service
public class CommonServiceImpl implements CommonService {
    @Autowired
    private StreetMapper streetMapper;

    @Override
    public List<Map<String,String>> queryAllProvince() {
        List<Map<String,String>> list = streetMapper.queryAllProvince();
        return list;
    }

    @Override
    public List<Map<String,String>> queryCityByCode(String code) {
        List<Map<String,String>> list = streetMapper.queryCityByCode(code);
        return list;
    }

    @Override
    public List<Map<String,String>> queryAreaByCode(String code) {
        List<Map<String,String>> list = streetMapper.queryAreaByCode(code);
        return list;
    }

    @Override
    public List<AddressTreeVO> queryAddressTree() {
        List<Map<String,String>> provinceList = streetMapper.queryAllProvince();
        List<Map<String,String>> cityList = streetMapper.queryAllCityList();
        List<Map<String,String>> areaList = streetMapper.queryAllAreaList();
        List<AddressTreeVO> tree = new ArrayList<>();

        for (Map<String, String> province : provinceList) {
            AddressTreeVO provinceNode = new AddressTreeVO(province.get("code"), province.get("name"), new ArrayList<>());

            for (Map<String, String> city : cityList) {
                if (province.get("code").equals(city.get("provinceCode"))) {
                    AddressTreeVO cityNode = new AddressTreeVO(city.get("code"), city.get("name"), new ArrayList<>());

                    for (Map<String, String> area : areaList) {
                        if (city.get("code").equals(area.get("city_code"))) {
                            AddressTreeVO areaNode = new AddressTreeVO(area.get("code"), area.get("name"),null);
                            cityNode.getChildren().add(areaNode);
                        }
                    }

                    provinceNode.getChildren().add(cityNode);
                }
            }

            tree.add(provinceNode);
        }

        return tree;
    }
}
